package programa.GUi;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

public class Acceso extends javax.swing.JFrame {

    public Connection con;
    private String separador = System.getProperty("file.separator");
    private String home = System.getProperty("user.home");
    private String base = "jdbc:derby:" + home + separador + "librarydb;create=true";
    private int prueba = 0;

    public Acceso() {
        initComponents();
        setLocationRelativeTo(null);
        conexion();
    }

    private void conexion() {
        try {
            //Cargar controlador
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            //Establecer la conexion
            con = DriverManager.getConnection(base);
            System.out.println("La base ha sido cargada " + base);
            crearTablas();
        } catch (SQLException ex) {
            System.out.println("problema con sql: " + ex);
        } catch (ClassNotFoundException ex) {
            JOptionPane.showMessageDialog(this, "Error al cargar Driver");
            System.exit(0);
        }

    }

    private void crearTablas() {
        try {
            Statement st = con.createStatement();
            //tabla de los empleados
            st.execute("CREATE TABLE Usuarios ("
                    + "id INT not null primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),"
                    + "Usuario VARCHAR(20),"
                    + "Empleado VARCHAR(20),"
                    + "Contraseña VARCHAR(14)"
                    + ")");

            st.execute("CREATE TABLE Alumnos("
                    + "id INT not null primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),"
                    + "Codigo    VARCHAR(30), "
                    + "Nombre   VARCHAR(20), "
                    + "Apellidos VARCHAR(20),"
                    + "Direccion VARCHAR(30),"
                    + "TipoUsuario VARCHAR(20)"
                    + ")");

            //tabla de registo de alumnos, profesores y otros

            //tabla de los libros
            st.execute("CREATE TABLE Libros ("
                    + "id INT not null primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),"
                    + "Codigo    VARCHAR(30) not null, "
                    + "Titulo    VARCHAR(30) not null, "
                    + "Autor    VARCHAR(30) not null, "
                    + "Editorial    VARCHAR(30) not null, "
                    + "Cantidad    VARCHAR(30) not null, "
                    + "Ubicacion    VARCHAR(30) not null"
                    + ")");

            //tabla de prestamos de libros
            st.execute("CREATE TABLE Prestamo ("
                    + "id INT not null primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),"
                    + "CodigoUsuario    VARCHAR(30), "
                    + "Usuario    VARCHAR(30), "
                    + "Apellidos  VARCHAR(30),"
                    + "Direccion VARCHAR(30),"
                    +"TipoUsuario VARCHAR(30),"
                    //datos del libro
                    + "CodigoLibro   VARCHAR(30), "
                    + "Titulo    VARCHAR(30), "
                    + "Autor    VARCHAR(30), "
                    + "Editorial    VARCHAR(30), "
                    + "Ubicacion    VARCHAR(30),"
                    +"Fecha    VARCHAR(30)"
                    + ")");
            
            st.execute("INSERT INTO Usuarios (Usuario,Empleado,Contraseña) VALUES ('" + "admin" + "','" + "administrador" + "','" + "admin" + "')");

        } catch (SQLException ex) {
            System.out.println("problema con sql: " + ex);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jPasswordField1 = new javax.swing.JPasswordField();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Acceso al sistema");

        jButton1.setBackground(new java.awt.Color(204, 153, 0));
        jButton1.setFont(new java.awt.Font("Georgia", 0, 14)); // NOI18N
        jButton1.setForeground(new java.awt.Color(255, 255, 255));
        jButton1.setText("Inicio");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Georgia", 0, 14)); // NOI18N
        jLabel3.setText("Usuario");

        jLabel4.setFont(new java.awt.Font("Georgia", 0, 14)); // NOI18N
        jLabel4.setText("Contraseña");

        jLabel2.setFont(new java.awt.Font("Ubuntu Light", 1, 36)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("¡Bienvenido!");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/mind-library.jpg"))); // NOI18N
        jLabel1.setAlignmentX(0.5F);
        jLabel1.setMaximumSize(new java.awt.Dimension(300, 150));
        jLabel1.setMinimumSize(new java.awt.Dimension(300, 150));
        jLabel1.setPreferredSize(new java.awt.Dimension(300, 150));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(54, 54, 54)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //comparacion de tipo de usuarios
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        verificarUsuario();
        if (prueba == 1) {
            //interfas del usuario
            JOptionPane.showMessageDialog(this, "Sesion Iniciada \ncomo empleado");
            new Gui().setVisible(true);
            Gui.jMenu5.setVisible(false);
            setVisible(false);
        } else if (prueba == 2) {
            //interfas del administrador
            JOptionPane.showMessageDialog(this, "Sesion Iniciada \ncomo administrador");
            new Gui().setVisible(true);
            setVisible(false);
        } else {
            //no esta registrado
            JOptionPane.showMessageDialog(this, "Usuario o Contraseña equivocados");
            jTextField1.setText(null);
            jPasswordField1.setText(null);
        }
    }//GEN-LAST:event_jButton1ActionPerformed
//metodo para validar el usuario

    public void verificarUsuario() {
        try {
            Statement st = con.createStatement();
            ResultSet rs;
            rs = st.executeQuery("SELECT Usuario,Empleado,Contraseña FROM Usuarios");
            while (rs.next()) {

                System.out.println(rs.getString("Usuario") + "-" + rs.getString("Empleado") + "-" + rs.getString("Contraseña"));
                String empleado = "empleado";
                String admin = "administrador";

                if (jTextField1.getText().equals(rs.getString("Usuario")) && (empleado.equals(rs.getString("Empleado"))) && jPasswordField1.getText().equals(rs.getString("Contraseña"))) {
                    prueba = 1;
                    //es un usuario
                } else if (jTextField1.getText().equals(rs.getString("Usuario")) && (admin.equals(rs.getString("Empleado"))) && jPasswordField1.getText().equals(rs.getString("Contraseña"))) {
                    prueba = 2;
                    //es un aadministrador
                }

            }
        } catch (SQLException e) {
            System.out.println("problema con sql: " + e);
        }
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Acceso().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
